<template>
  <div>
    <el-form
      ref="shopFormRef"
      :model="shopForm"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="店铺名称" prop="shopName">
            <el-input v-model="shopForm.shopName"></el-input>
          </el-form-item>
          <el-form-item label="店铺地址" prop="shopAddress">
            <el-input v-model="shopForm.shopAddress"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="shopForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="营业时间" prop="yingyeTime">
            <el-input v-model="shopForm.yingyeTime"></el-input>
          </el-form-item>
          <el-form-item label="经营范围" prop="jingyingfw">
            <el-input v-model="shopForm.jingyingfw"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="fuzer">
            <el-input v-model="shopForm.fuzer"></el-input>
          </el-form-item>
          <el-form-item label="店铺面积" prop="dianpumj">
            <el-input-number
              v-model.number="shopForm.dianpumj"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="开店日期" prop="shopDate">
            <el-date-picker
              v-model="shopForm.shopDate"
              type="date"
              placeholder="选择开店日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="shopForm.email"></el-input>
          </el-form-item>
          <el-form-item label="所在区域" prop="region">
            <el-input v-model="shopForm.region"></el-input>
          </el-form-item>
          <el-form-item label="是否连锁" prop="liansuo">
            <el-switch v-model="shopForm.liansuo"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="店铺网址" prop="wangAddress">
        <el-input v-model="shopForm.wangAddress"></el-input>
      </el-form-item>
      <el-form-item label="客服电话" prop="kefuPhone">
        <el-input v-model="shopForm.kefuPhone"></el-input>
      </el-form-item>
    </el-form>
    <div style="text-align: center; margin-top: 20px">
      <el-button @click="showMapDialog">选择店铺位置</el-button>
      <!-- 地图弹框组件 -->
      <MapDialog v-model="mapVisible" @confirm="handleAddressConfirm" />
      <el-button type="primary" @click="submitShopForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, defineProps, defineEmits, Ref } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import http from '../../api/http'
import MapDialog from "../Address/Window.vue";

// 定义表单数据类型
interface ShopForm {
  shopName: string
  shopAddress: string
  phone: string
  yingyeTime: string
  jingyingfw: string
  fuzer: string
  dianpumj: number
  shopDate: string | null
  email: string
  region: string
  liansuo: boolean
  wangAddress: string
  kefuPhone: string
}

// 定义地图选择返回数据类型
interface AddressData {
  name: string
  address: string
}

// 定义组件属性
const props = defineProps({
  dialogFormVisible: {
    type: Boolean,
    default: false
  }
})

// 定义组件事件
const emit = defineEmits<{
  (e: 'change', value: boolean): void
  (e: 'refresh'): void
}>()

// 表单引用
const shopFormRef = ref<InstanceType<typeof ElForm>>()

// 响应式数据
const mapVisible = ref(false)
const selectedAddress = ref("")
const shopForm = reactive<ShopForm>({
  shopName: "",
  shopAddress: "",
  phone: "",
  yingyeTime: "",
  jingyingfw: "",
  fuzer: "",
  dianpumj: 0,
  shopDate: null,
  email: "",
  region: "",
  liansuo: false,
  wangAddress: "",
  kefuPhone: "",
})

// 表单验证规则
const rules = reactive({
  shopName: [
    { required: true, message: "请输入店铺名称", trigger: "blur" },
  ],
  shopAddress: [
    { required: true, message: "请输入店铺地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" }
  ],
  dianpumj: [
    { type: "number", message: "请输入有效的店铺面积", trigger: "blur" },
  ],
  shopDate: [
    { required: true, message: "请选择开店日期", trigger: "change" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
})

// 显示地图弹窗
const showMapDialog = () => {
  mapVisible.value = true
}

// 处理地址选择确认
const handleAddressConfirm = (addressData: AddressData) => {
  selectedAddress.value = `${addressData.name} (${addressData.address})`
  shopForm.shopName = addressData.name
  shopForm.shopAddress = addressData.address
}

// 提交表单
const submitShopForm = () => {
  shopFormRef.value?.validate((valid) => {
    if (valid) {
      http.post('HJQ_store_info', shopForm)
        .then((response) => {
          if (response.code === "200") {
            ElMessage.success("店铺信息添加成功")
            resetForm()
            emit('refresh')      // 通知父组件刷新数据
            emit('change', false) // 关闭弹窗
          } else {
            ElMessage.error(`店铺信息添加失败：${response.msg || '未知错误'}`)
          }
        })
        .catch((error) => {
          console.error("Error adding shop:", error)
          ElMessage.error("店铺信息添加失败：网络错误，请稍后重试")
        })
    } else {
      console.log("表单验证不通过")
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  shopFormRef.value?.resetFields()
  // 手动重置日期等特殊字段
  shopForm.shopDate = null
}

// 监听弹窗显示状态变化
watch(() => props.dialogFormVisible, (newVal) => {
  if (!newVal) {
    resetForm()
  }
})
</script>

<style scoped>
.el-form-item {
  margin-bottom: 15px;
}
</style>
